package cn.iocoder.yudao.module.design.service.taskactionInterface;

import cn.hutool.core.convert.Convert;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.design.controller.admin.flowtask.vo.FlowTaskBaseVO;
import cn.iocoder.yudao.module.design.dal.dataobject.flow.FlowDO;
import cn.iocoder.yudao.module.design.dal.dataobject.flowtask.FlowTaskDO;
import cn.iocoder.yudao.module.design.dal.dataobject.houseUserRel.HouseUserRelDO;
import cn.iocoder.yudao.module.design.dal.mysql.flowtask.FlowTaskMapper;
import cn.iocoder.yudao.module.design.dal.mysql.house.HouseMapper;
import cn.iocoder.yudao.module.design.dal.mysql.houseUserRel.HouseUserRelMapper;
import cn.iocoder.yudao.module.design.service.flow.FlowService;
import cn.iocoder.yudao.module.design.service.house.HouseService;
import cn.iocoder.yudao.module.design.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.design.enums.design.FlowCdEnum;
import cn.iocoder.yudao.module.design.enums.design.FlowTaskStatusEnum;
import cn.iocoder.yudao.module.design.enums.design.UserRelStatusCdEnum;
import cn.iocoder.yudao.module.design.enums.user.DesignUserRoleEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

/**
 * 项目关联申请
 */
@Service
@Validated
@Slf4j
public class HouseUserRelTaskActionImpl implements  FlowTaskActionInterface{

    @Resource
    private FlowTaskMapper flowTaskMapper;
    @Resource
    private HouseMapper houseMapper;

    @Resource
    private HouseUserRelMapper houseUserRelMapper;


    @Resource
    private FlowService flowService;

    @Resource
    private HouseService houseService;



    /**
     * 任务处理-同意-流转
     *
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmAction(Object obj){
        final FlowTaskBaseVO vo = Convert.convert(FlowTaskBaseVO.class, obj);

        // 查询当前任务明细
        FlowTaskDO flowTaskDO = flowTaskMapper.selectById(vo.getId());
        if(flowTaskDO==null){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.TASK_NOT_EXIST_DATA_ERROR);
//            throw new NullPointerException("任务不存在,数据错误");
        }

        // 判断是不是本人处理
        final Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        if(!loginUserId.equals(flowTaskDO.getDealerId())){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.NOT_OPTION_SELF_DATA);
//            throw new NullPointerException("不允许非本人处理数据！！！");
        }
        // 修改任务为已同意

        flowTaskDO.setStatusCd(FlowTaskStatusEnum.FLOW_STATUS_ENUM_2.getCode());
        flowTaskMapper.updateById(flowTaskDO);

        // 关联人状态修改正常
        final Long houseId = flowTaskDO.getHouseId();
        final Long dealerId = flowTaskDO.getDealerId();
        Integer roleId = flowTaskDO.getFlowCd();
        QueryWrapper query = new QueryWrapper();
        query.eq("house_id",houseId);
        query.eq("user_id",dealerId);
        // 关联人处理的时候是 roleId = flowCd
        query.eq("role_id",roleId);
        query.eq("status", UserRelStatusCdEnum.USER_REL_STATUS_CD_0.getCode());
        HouseUserRelDO houseUserRelDO = houseUserRelMapper.selectOne(query);
        if(houseUserRelDO!=null){
            HouseUserRelDO updateDO = new HouseUserRelDO();
            updateDO.setStatus(UserRelStatusCdEnum.USER_REL_STATUS_CD_1.getCode().toString());
            query = new QueryWrapper();
            query.eq("house_id",houseId);
            query.eq("user_id",dealerId);
            query.eq("status", UserRelStatusCdEnum.USER_REL_STATUS_CD_0.getCode());
            houseUserRelMapper.update(updateDO,query);
        }else{
            // 在采购页面单独添加关联人是没有houseId 无法创建请求的所以为空
            // 在这里创建数据
            houseUserRelDO = new HouseUserRelDO();
            houseUserRelDO.setHouseId(houseId);
            houseUserRelDO.setUserId(dealerId);
            houseUserRelDO.setRoleId(Long.valueOf(roleId));
            houseUserRelDO.setStatus(UserRelStatusCdEnum.USER_REL_STATUS_CD_1.getCode().toString());
            houseUserRelDO.setDeleted(false);
            houseUserRelMapper.insert(houseUserRelDO);
//          throw ServiceExceptionUtil.exception(ErrorCodeConstants.RELATION_DATA_NOT_EXIST);
        }
        // 业主 材料管家 项目经理 供应商 商务 客服 添加对应的userFlowRel 关联数据
         saveUserFlowRel(houseId,dealerId,Long.valueOf(roleId));

        // 判断是否有待办任务是否待开始  有则改为开始
        FlowTaskDO flowTaskDO1 = new FlowTaskDO();
        flowTaskDO1.setStatusCd(FlowTaskStatusEnum.FLOW_STATUS_ENUM_1.getCode());
        QueryWrapper<FlowTaskDO> flowTaskDOQueryWrapper = new QueryWrapper<>();
        // 查询待开始的待办任务
        flowTaskDOQueryWrapper.eq("house_id",houseId);
        flowTaskDOQueryWrapper.eq("dealer_id",dealerId);
        flowTaskDOQueryWrapper.eq("status_cd",FlowTaskStatusEnum.FLOW_STATUS_ENUM_0.getCode());
        flowTaskMapper.update(flowTaskDO1,flowTaskDOQueryWrapper);
    }

    /**
     * 任务处理-拒绝-回退
     *
     */
    @Override
    public void refuseAction(Object obj){
        final FlowTaskBaseVO vo = Convert.convert(FlowTaskBaseVO.class, obj);

        // 查询当前任务明细
        FlowTaskDO flowTaskDO = flowTaskMapper.selectById(vo.getId());
        if(flowTaskDO==null){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.TASK_NOT_EXIST_DATA_ERROR);
//            throw new NullPointerException("任务不存在,数据错误");
        }

        // 判断是不是本人处理
        final Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        if(!loginUserId.equals(flowTaskDO.getDealerId())){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.NOT_OPTION_SELF_DATA);
//            throw new NullPointerException("不允许非本人处理数据！！！");
        }
        // 修改任务为已拒绝

        flowTaskDO.setStatusCd(FlowTaskStatusEnum.FLOW_STATUS_ENUM_3.getCode());
        flowTaskMapper.updateById(flowTaskDO);

        // 关联人状态修改正常
        final Long houseId = flowTaskDO.getHouseId();
        final Long dealerId = flowTaskDO.getDealerId();
        Integer roleId = flowTaskDO.getFlowCd();
        QueryWrapper query = new QueryWrapper();
        query.eq("house_id",houseId);
        query.eq("user_id",dealerId);
        query.eq("role_id",roleId);
        query.eq("status",UserRelStatusCdEnum.USER_REL_STATUS_CD_1.getCode());
        final HouseUserRelDO houseUserRelDO = houseUserRelMapper.selectOne(query);
        if(houseUserRelDO!=null){
            houseUserRelDO.setStatus(UserRelStatusCdEnum.USER_REL_STATUS_CD_2.getCode().toString());
            houseUserRelMapper.updateBatch(houseUserRelDO);
        }else{
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.RELATION_DATA_NOT_EXIST);
//            throw new NullPointerException("关联人数据不存在");
        }


    }

    /**
     * 任务处理-查看
     *
     */
    @Override
    public Object viewAction(Object obj){
        final FlowTaskBaseVO vo = Convert.convert(FlowTaskBaseVO.class, obj);

        return null;
    }

    /**
     * 任务补充
     *
     */
    @Override
    public void replenishTask(Object obj){

    }

void saveUserFlowRel(Long houseId,Long userId,Long roleId){
    List<FlowDO> flowAll = flowService.getFlowAll(houseId);
    for (FlowDO flow:flowAll  ) {
        if(DesignUserRoleEnum.PROJECT_MANAGER.getRoleId().equals(roleId)&&FlowCdEnum.FLOW_CD_2.getCode().equals(flow.getFlowCd())){
            houseService.saveHouseUserFlowRel(houseId,flow.getId(),userId,DesignUserRoleEnum.PROJECT_MANAGER.getRoleId());
            return ;
        }
        // 供应商 暂不处理
        if(DesignUserRoleEnum.SUPPLIER.getRoleId().equals(roleId)|| DesignUserRoleEnum.PRINCIPAL.getRoleId().equals(roleId)){
            return ;
        }
        //业主 材料管家 客服 所有流程都加入
        houseService.saveHouseUserFlowRel(houseId,flow.getId(),userId,roleId);
    }

}


}
